package com.yehuo.app.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yehuo.app.entity.Order;
import com.yehuo.app.entity.Wallet;
import com.yehuo.app.mapper.AppOrderMapper;
import com.yehuo.app.mapper.OrderMapper;
import com.yehuo.app.mapper.WalletMapper;
import com.yehuo.app.model.APP;
import com.yehuo.app.service.AppOrderService;
import com.yehuo.app.util.wx.constants.WXPayConstants;
import com.yehuo.app.util.wx.util.WXPayUtil;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping({"/weixin/pay"})
public class WXPayController {
    private static final Logger log = LoggerFactory.getLogger(WXPayController.class);
    @Autowired
    private AppOrderMapper orderMapper;
    @Autowired
    private WalletMapper walletMapper;
    @Autowired
    private AppOrderService orderService;
    private String resSuccessXml = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
    private String resFailXml = "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[报文为空]]></return_msg></xml>";

    public WXPayController() {
    }

    @RequestMapping({"/wxnotify"})
    public void wxnotify(HttpServletRequest request, HttpServletResponse response) {
        String resXml = "";
        boolean var21 = false;
        BufferedOutputStream out;
        label148: {
            try {
                var21 = true;
                InputStream inStream = request.getInputStream();
                ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                boolean var7 = false;

                int len;
                while((len = inStream.read(buffer)) != -1) {
                    outSteam.write(buffer, 0, len);
                }

                WXPayUtil.getLogger().info("wxnotify:微信支付----start----");
                String result = new String(outSteam.toByteArray(), "utf-8");
                WXPayUtil.getLogger().info("wxnotify:微信支付----result----=" + result);
                outSteam.close();
                inStream.close();
                Map<String, String> map = WXPayUtil.xmlToMap(result);
                boolean isSuccess = false;
                if ("SUCCESS".equalsIgnoreCase(map.get("result_code"))) {
                    WXPayUtil.getLogger().info("wxnotify:微信支付----返回成功");
                    if (WXPayUtil.isSignatureValid(map, WXPayConstants.API_KEY)) {
                        WXPayUtil.getLogger().info("wxnotify:微信支付----验证签名成功");
                        resXml = this.resSuccessXml;
                        isSuccess = true;
                    } else {
                        WXPayUtil.getLogger().error("wxnotify:微信支付----判断签名错误");
                    }
                } else {
                    WXPayUtil.getLogger().error("wxnotify:支付失败,错误信息：" + map.get("err_code_des"));
                    resXml = this.resFailXml;
                }

                String out_trade_no = map.get("out_trade_no");
                QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
                orderQueryWrapper.eq("order_no",out_trade_no);
                Order order = this.orderMapper.selectOne(orderQueryWrapper);
                if (isSuccess) {
                    if (order != null) {
                        if (4 == order.getOrderType()) {
                            order.setPayType(2);
                            order.setBalance(1);
                            order.setStatus(3);
                            order.setUpdateTime(new Date());
                            order.setEndTime(order.getUpdateTime());
                            this.orderMapper.updateById(order);
                            Wallet wallet = this.walletMapper.selectByUserId(order.getUserId());
                            if (wallet == null) {
                                wallet = new Wallet();
                                wallet.setAmount("0.00");
                                wallet.setConsumptionAmount(wallet.getAmount());
                                wallet.setCreateTime(new Date());
                                wallet.setUpdateTime(wallet.getCreateTime());
                                wallet.setRechargeAmount(wallet.getRechargeAmount());
                                wallet.setUserId(order.getUserId());
                                this.walletMapper.insert(wallet);
                            }

                            this.walletMapper.updateAddAmount(wallet.getId(), order.getAmount(), new Date());
                            var21 = false;
                        } else {
                            var21 = false;
                        }
                    } else {
                        var21 = false;
                    }
                } else if (order != null) {
                    if (4 == order.getOrderType()) {
                        order.setPayType(2);
                        order.setBalance(1);
                        order.setStatus(4);
                        order.setUpdateTime(new Date());
                        order.setEndTime(order.getUpdateTime());
                        this.orderMapper.updateById(order);
                        var21 = false;
                    } else {
                        var21 = false;
                    }
                } else {
                    var21 = false;
                }
                break label148;
            } catch (Exception var25) {
                WXPayUtil.getLogger().error("wxnotify:支付回调发布异常：", var25);
                var21 = false;
            } finally {
                if (var21) {
                    try {
                        out = new BufferedOutputStream(response.getOutputStream());
                        out.write(resXml.getBytes());
                        out.flush();
                        out.close();
                    } catch (IOException var22) {
                        WXPayUtil.getLogger().error("wxnotify:支付回调发布异常:out：", var22);
                    }

                }
            }

            try {
                out = new BufferedOutputStream(response.getOutputStream());
                out.write(resXml.getBytes());
                out.flush();
                out.close();
            } catch (IOException var23) {
                WXPayUtil.getLogger().error("wxnotify:支付回调发布异常:out：", var23);
            }

            return;
        }

        try {
            out = new BufferedOutputStream(response.getOutputStream());
            out.write(resXml.getBytes());
            out.flush();
            out.close();
        } catch (IOException var24) {
            WXPayUtil.getLogger().error("wxnotify:支付回调发布异常:out：", var24);
        }

    }

    @PostMapping({"/doWxOrder"})
    public APP doWxOrder(HttpServletRequest request, String userId, String orderId) {
        return this.orderService.doWxOrder(request, userId, orderId);
    }

    @PostMapping({"/getPrepayId"})
    public APP getPrepayId(HttpServletRequest request, String userId, String orderId) {
        return this.orderService.getPrepayId(request, userId, orderId);
    }
}

